import axios, { type AxiosRequestHeaders } from "axios";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import pinia from "@/stores/index";
import { useUserInfoStore } from "../stores/userInfo";
import { ElNotificationFn } from "./computedUtils";
const userApiAddress = ['/plate/login','/plate/user/save','/plate/userInfo','/plate/logout']
const getApiAddress = ()=>{
  if(import.meta.env.MODE === "development"){
    if(localStorage.getItem('apiEnvironment') === 'local'){
      return "http://192.168.5.24:8895"
    }else{
      return "http://192.168.5.71:8895"
    }
  }else{
    return window.apiAddress.baseUrl
  }
}
const request = axios.create({
  baseURL: getApiAddress(),
});
const fileUploadUrls:any = ['/deploymentUnit/addMinIO','/deploymentUnit/addStartScript']
request.interceptors.request.use((config:any) => {
    const userInfoStore = useUserInfoStore(pinia)
    const token = userInfoStore.token
    config.baseURL = getApiAddress()
    if(!userApiAddress.includes(config.url)&&localStorage.getItem('apiEnvironment') !== 'local'){
       config.baseURL = "http://192.168.5.71:9999"
    }

    if(!userApiAddress.includes(config.url)&&localStorage.getItem('apiEnvironment') === 'local'){
      config.baseURL = "http://192.168.5.24:9999"
    }


    if(!fileUploadUrls.includes(config.url)){
       config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    if(token){
        (config.headers as AxiosRequestHeaders )['Authorization'] ='Bearer '+ token
      }
     NProgress.start();
     return config;
});
request.interceptors.response.use(
  async (response:any) => {
    NProgress.done();
    const res = response.data;
    if (res.code != 200) {  
      ElNotificationFn("error",res.msg || "Error");
      return Promise.reject(new Error(res.msg || "Error"));
    }
    return res;
  },
  (error:any) => {
   NProgress.done();
   if (error.message.indexOf("timeout") != -1) {
    ElNotificationFn("error","网络超时");
  } else if (error.message == "Network Error") {
    ElNotificationFn("error","网络连接错误");
  } else {
    if (error.response.data) ElNotificationFn("error",error.response.statusText);
    else ElNotificationFn("error","接口路径找不到");
  }
  return Promise.reject(error);
  }
);

export default request;
